import axios from 'axios'; 
import { Toast } from 'mint-ui';


const setTime = function() {
	let userInfo = window.localStorage.getItem('userInfo');
	if (userInfo && userInfo != 'undefined') {
		var deadTime = +new Date() + 2 * 60 * 60 * 1000;
		window.localStorage.setItem('deadTime', deadTime);
	}
}

/**
 * axios ge请求
 * @param  {[string]} url [请求路径]
 * @param  {[Object]} obj [请求传递参数]
 * @return {[Promise]}    [description]
 */
export const axiosGet = (url, obj, cb, msg, fn) => { 
	msg = msg || '请求失败';
	return axios({
			url: url,
			method: 'get',
			params: obj,
			withCredentials: true,
			timeout: 10000
		})
		.then(json => {
			setTime();
			cb(json.data);
		})
		.catch(() => {
			// Toast(msg);
			if (fn) fn();
		});
};

/**
 * axios post请求
 * @param  {[string]} url [请求路径]
 * @param  {[Object]} obj [请求传递参数]
 * @return {[Promise]}    [description]
 */
export const axiosPost = (url, obj, cb, msg, fn) => {
	msg = msg || '请求失败';
	return axios({
		url: url,
		method: 'post',
		data: obj,
		withCredentials: true,
		timeout: 10000
	})
	.then(res => {
		setTime();
		cb(res.data);
	})
	.catch((e) => {
		console.error(e); 
		Toast(msg);
		if (fn) fn();
	})
}; 

export const setSessionStorage = (name, val) => {
	window.sessionStorage.setItem(name, val)
}

export const getSessionStorage = (name, type) => {
	var val = window.sessionStorage.getItem(name);

	if (!type || !val) {
		return val; 
	}

	if (val && type.toUpperCase() == 'ARRAY') {
		return val.split(',');
	}

	if (val && type.toUpperCase() == 'OBJECT') {
		return JSON.parse(val);
	}
}
 